package cn.edu.zjicm.wordsnet_d.activity;

import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnticipateOvershootInterpolator;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.BroadcastReceiver.AlarmReceiver;
import cn.edu.zjicm.wordsnet_d.BroadcastReceiver.HomeKeyEventBroadCastReceiver;
import cn.edu.zjicm.wordsnet_d.activity.base.BaseMenuActivity;
import cn.edu.zjicm.wordsnet_d.data.DataManager;
import cn.edu.zjicm.wordsnet_d.data.OneWord;
import cn.edu.zjicm.wordsnet_d.data.StaticData;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference.BookType;
import cn.edu.zjicm.wordsnet_d.datapersistent.FileManager;
import cn.edu.zjicm.wordsnet_d.db.WordFactory;
import cn.edu.zjicm.wordsnet_d.download.JudgeNetwork;
import cn.edu.zjicm.wordsnet_d.download.UpdateManager;
import cn.edu.zjicm.wordsnet_d.lock.LockService;
import cn.edu.zjicm.wordsnet_d.synchronize.UserInterface;
import cn.edu.zjicm.wordsnet_d.util.DateTimeUtils;
import cn.edu.zjicm.wordsnet_d.util.LogUtil;
import cn.edu.zjicm.wordsnet_d.util.NightModeUtil;
import cn.edu.zjicm.wordsnet_d.util.Utils;
import cn.edu.zjicm.wordsnet_d.view.MyDialog;
import cn.edu.zjicm.wordsnet_d.view.RoundProgress;
import cn.edu.zjicm.wordsnet_d.view.VariableTextView;

import com.umeng.analytics.MobclickAgent;

public class MainActivity extends BaseMenuActivity {

	public static void startActivity(Context context) {
		LogUtil.d("调用MainActivity.startActivity()");
		Intent i = new Intent(context, MainActivity.class);
		context.startActivity(i);
		if (GuideActivityFull.mInstance != null) {
			GuideActivityFull.mInstance.toFinish();
		}
	}

	private static MainActivity instance;
	private Button startStudyButton, consolidationButton, startReviewButton;
	private LinearLayout startHuanboButton, difficultyWordsButton, wordsFmDegreeButton;
	private WordFactory wf;
	private int unlearnedWordsNum, unfamiliarWordsNum, familiarWordsNum, easyWordsNum;
	private static Context mContext;
	private DataToRestActivity mDataToMainActivity;
	public static HomeKeyEventBroadCastReceiver receiver;

	private RoundProgress roundProgress;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = MainActivity.this;
		if (AppPreference.getLoginID(this) == "") {
			Log.e("not login", "not login");
			finish();
			return;
		}

		if (AppPreference.getWordBookIndex(this) == -1 && AppPreference.getPhraseBookIndex(this) == -1) {
			Log.e("not set book", "not set book");
			finish();
			return;
		}
		// 设定调整音量为媒体音量
		setVolumeControlStream(AudioManager.STREAM_MUSIC);
		processIntent();
		wf = WordFactory.getInstance(mContext);

		setContentView(R.layout.activity_main);
		instance = this;

		findViews();
		initViews();
		studyMode();

		// 先判断是否需要提醒用户下载知米听力，如果不需要，再判断是否需要提醒用户登录，如果不需要，再查看是否需要提醒用户升级，三者只做其一
		if (!autoRecommendZhimiListen(mContext))
			if (!autoCheckLogin(mContext))
				UpdateManager.autoCheckUpdate(this);

		// 判断压缩包是否存在
		if (FileManager.hasNotDownloadedVoicePack(this, true))
			Toast.makeText(this, "有部分音频文件没有下载，可能会影响听音，建议去设置页面下载", Toast.LENGTH_LONG).show();

		// 启动锁屏服务
		LockService.startActivity(this);
		if (!AppPreference.isInitForConsolidate(mContext)) {
			DataManager.getInstance().initForConsilidate(mContext);
			AppPreference.setInitForConsolidate(mContext, true);
		}
		resetConsolidateBtnState();
	}

	// 提醒用户下载知米听力
	public boolean autoRecommendZhimiListen(Context mContext) {
		if (AppPreference.isShowRecommendZhimiListen(mContext))
			return false;
		else {
			JudgeNetwork jNetwork = JudgeNetwork.getInstance(mContext);
			if (jNetwork.isMobileConnected() || jNetwork.isWifiConnected()) {
				mHandler.sendMessage(mHandler.obtainMessage(1));
				AppPreference.setShowRecommendZhimiListen(mContext, true);
				return true;
			} else
				return false;
		}
	}

	// 软件提醒登录,用户使用软件3天后或者用户的单词本中的单词数>=100时，会自动提醒用户登录帐号
	public boolean autoCheckLogin(Context mContext) {
		if (UserInterface.getInstance(mContext).isLogin())
			return false;

		int logCount = WordFactory.getInstance(mContext).getWordsLogCount();
		int lastAutoCheckLoginDate = AppPreference.getAutoCheckLoginDate(mContext);

		if (lastAutoCheckLoginDate == -1) {
			if (logCount >= 100)
				return checkLogin();
			else {
				AppPreference.setAutoCheckLoginDate(mContext, DateTimeUtils.getDate());
				return false;
			}
		}

		int theDayBeforeYestorday = DateTimeUtils.getTheDayBeforeYestorday();
		boolean result = false;
		if (lastAutoCheckLoginDate < theDayBeforeYestorday) {
			result = checkLogin();
		}
		return result;
	}

	boolean checkLogin() {
		boolean result = false;
		JudgeNetwork jNetwork = JudgeNetwork.getInstance(mContext);
		if (jNetwork.isMobileConnected() || jNetwork.isWifiConnected()) {
			mHandler.sendMessage(mHandler.obtainMessage(0));
			result = true;
			AppPreference.setAutoCheckLoginDate(mContext, DateTimeUtils.getDate());
		}
		return result;
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (!((Activity) mContext).isFinishing()) {
				switch (msg.what) {
				case 0:
					mHandler.post(askLoginThread);
					break;
				case 1:
					mHandler.post(recomentdZhimiListenThread);
					break;
				}
			}
		};
	};

	private Runnable askLoginThread = new Runnable() {
		public void run() {
			showAskLoginWindow();
		}
	};

	private MyDialog mAskLoginWindow;

	private void showAskLoginWindow() {
		View view = View.inflate(mContext, R.layout.window_ask_login, null);
		if (mAskLoginWindow == null) {
			// init PopWindow cotentview
			TextView registerConfirmButton = (TextView) view.findViewById(R.id.register_button);
			TextView registerCancleButton = (TextView) view.findViewById(R.id.register_cancel_button);
			TextView loginButton = (TextView) view.findViewById(R.id.login);
			registerConfirmButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mAskLoginWindow.dismiss();
					mAskLoginWindow = null;
					RegisterActivity.startActivity(mContext, RegisterActivity.TO_MAIN);
				}
			});
			registerCancleButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mAskLoginWindow.dismiss();
					mAskLoginWindow = null;
				}
			});
			loginButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mAskLoginWindow.dismiss();
					mAskLoginWindow = null;
					LoginActivity.startActivity(mContext, false);
				}
			});

			mAskLoginWindow = new MyDialog(this, view, R.style.mydialog, false);
			mAskLoginWindow.setCanceledOnTouchOutside(true);
		}
		mAskLoginWindow.show();
	}

	private Runnable recomentdZhimiListenThread = new Runnable() {
		public void run() {
			showRecomentdZhimiListenWindow();
		}
	};

	private MyDialog mRecomentdZhimiListenWindow;

	private void showRecomentdZhimiListenWindow() {
		View view = View.inflate(mContext, R.layout.window_recommend_zhimi_listen, null);
		if (mRecomentdZhimiListenWindow == null) {
			TextView downloadConfirmButton = (TextView) view.findViewById(R.id.download_button);
			TextView downloadCancleButton = (TextView) view.findViewById(R.id.download_cancel_button);
			TextView hintText = (TextView) view.findViewById(R.id.zhimi_listen_hint_tv);
			hintText.setText(Utils.ToDBC(getResources().getString(R.string.recommend_zhimi_listen_hint)));
			downloadCancleButton.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); // 下划线
			downloadConfirmButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mRecomentdZhimiListenWindow.dismiss();
					mRecomentdZhimiListenWindow = null;
					UpdateManager.downloadZhimiListenExludingMarket(mContext);
				}
			});
			downloadCancleButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mRecomentdZhimiListenWindow.dismiss();
					mRecomentdZhimiListenWindow = null;
				}
			});
			mRecomentdZhimiListenWindow = new MyDialog(this, view, R.style.mydialog, false);
			mRecomentdZhimiListenWindow.setCanceledOnTouchOutside(true);
			mRecomentdZhimiListenWindow.show();
		}
		mRecomentdZhimiListenWindow.show();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

		if (AppPreference.getLoginID(this) == "") {
			Log.e("not login", "not login");
			finish();
			return;
		}
		if (AppPreference.getWordBookIndex(this) == -1 && AppPreference.getPhraseBookIndex(this) == -1) {
			Log.e("not set book", "not set book");
			finish();
			return;
		}

		setIntent(intent);
		processIntent();
	}

	void processIntent() {
		int startMode = this.getIntent().getIntExtra("start_mode", 0);
		if (startMode == 1) {
			ExamRunActivity.startActivity(mContext, OneWord.DEGREE_UNFAMILIAR, ExamRunActivity.STUDY_MODE);
			return;
		}
	}

	@Override
	protected void onResume() {
		super.onResume();

		if (AppPreference.getLoginID(this) == "") {
			Log.e("not login", "not login");
			finish();
			return;
		}
		if (AppPreference.getWordBookIndex(this) == -1 && AppPreference.getPhraseBookIndex(this) == -1) {
			Log.e("not set book", "not set book");
			finish();
			return;
		}

		mDataToMainActivity = DataToRestActivity.getInstance();
		try {
			if (mDataToMainActivity != null && mDataToMainActivity.isIstrue()) {
				// openDialog();
				mDataToMainActivity.setIstrue(false);
			}
		} catch (Exception e) {
			e.printStackTrace();
			Log.i("MainActivity抛出异常", "");
		}

		MobclickAgent.onResume(this);

		if (mDataToMainActivity.isDBChanged()) {
			mDataToMainActivity.setDBChanged(false);
			int unlearnedWordsNum1 = AppPreference.getNewWordsFmDegree(this, 0);
			int unfamiliarWordsNum1 = 0;
			for (int i = 1; i <= WordFactory.wordReviewTime.length - 2; i++) {
				unfamiliarWordsNum1 += AppPreference.getNewWordsFmDegree(this, i);
			}
			int familiarWordsNum1 = AppPreference.getNewWordsFmDegree(this, WordFactory.wordReviewTime.length - 1);
			int easyWordsNum1 = AppPreference.getNewWordsFmDegree(this, 6);
			if (unlearnedWordsNum != unlearnedWordsNum1 || unfamiliarWordsNum != unfamiliarWordsNum1 || familiarWordsNum != familiarWordsNum1 || easyWordsNum != easyWordsNum1) {
				unlearnedWordsNum = unlearnedWordsNum1;
				unfamiliarWordsNum = unfamiliarWordsNum1;
				familiarWordsNum = familiarWordsNum1;
				easyWordsNum = easyWordsNum1;
				// mPieChartView.resetNum(unfamiliarWordsNum, familiarWordsNum,
				// unlearnedWordsNum, easyWordsNum, leftDays);
			}
		}
		studyMode();
		resetConsolidateBtnState();
		AlarmReceiver.cancleNotifyStudy(this);
		setMainDisplayData();
	}

	private void setMainDisplayData() {
		boolean hasWordTask = false, hasPhraseTask = false;
		int wordLeftDays = 0, phraseLeftDays = 0;
		int wordUnlearnCount = 0, phraseUnlearnCount = 0, wordAllCount = 0, phraseAllCount = 0;
		if (AppPreference.getWordBookIndex(mContext) != -1 && AppPreference.getWordBookIsLearning(mContext)) {
			LogUtil.d("正在学习单词书");
			hasWordTask = true;
			wordUnlearnCount = wf.getUnLearnedWordCount(AppPreference.getWordBookIndex(mContext));
			wordAllCount = wf.getWordCountInBook(AppPreference.getWordBookIndex(mContext));
			wordLeftDays = DateTimeUtils.getLeftDays(mContext, BookType.BOOK_WORD, wordUnlearnCount);
		}
		if (AppPreference.getPhraseBookIndex(mContext) != -1 && AppPreference.getPhraseBookIsLearning(mContext)) {
			LogUtil.d("正在学习词组书");
			hasPhraseTask = true;
			phraseUnlearnCount = wf.getUnLearnedWordCount(AppPreference.getPhraseBookIndex(mContext));
			phraseAllCount = wf.getWordCountInBook(AppPreference.getPhraseBookIndex(mContext));
			phraseLeftDays = DateTimeUtils.getLeftDays(mContext, BookType.BOOK_PHRASE, phraseUnlearnCount);
		}

		int degree = (int) ((wordAllCount + phraseAllCount - wordUnlearnCount - phraseUnlearnCount) * 1.0f / (wordAllCount + phraseAllCount) * 100);
		roundProgressAnimation(degree);
		// 这里第一二个参数分别表示是否在主界面显示单词剩余天数以及词组剩余天数，第三四个参数对应2个天数的值，后面三个参数看名字就可以；
		initDisplays(hasWordTask, hasPhraseTask, wordLeftDays, phraseLeftDays, unfamiliarWordsNum, familiarWordsNum, unlearnedWordsNum);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@SuppressLint("NewApi")
	private void resetConsolidateBtnState() {
		if (wf.getConsolidateWordsNum() > 0) {
			// 学习任务已经完成，巩固熟词任务没有完成
			if (wf.getNumberOfWordsForTestOfDegree(OneWord.DEGREE_UNFAMILIAR) <= 0) {
				if (NightModeUtil.isNightModeNow()) {
					consolidationButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.rectangle_green_button));
					consolidationButton.setTextColor(getResources().getColor(R.color.word_color_night));
				} else {
					consolidationButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.green_button_selector));
					consolidationButton.setTextColor(getResources().getColor(R.color.green_button_text_color_selector));
				}
			} else {// 学习任务没有完成，巩固熟词任务没有完成
				if (NightModeUtil.isNightModeNow()) {
					consolidationButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.rectangle_gray_button));
					consolidationButton.setTextColor(getResources().getColor(R.color.word_color_night));
				} else {
					consolidationButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.gray_button_selector));
					consolidationButton.setTextColor(getResources().getColor(R.color.main_text_color2));
				}
			}
		} else {// 没有熟词需要巩固
			if (NightModeUtil.isNightModeNow()) {
				consolidationButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.rectangle_gray_button));
			} else {
				consolidationButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.gray_button_selector));
			}
			consolidationButton.setTextColor(getResources().getColor(R.color.word_color_night));
		}
	}

	@SuppressLint("NewApi")
	private void findViews() {
		findViewsForNumDisplay();
		unlearnedWordsNum = AppPreference.getNewWordsFmDegree(this, 0);
		unfamiliarWordsNum = 0;
		for (int i = 1; i <= WordFactory.wordReviewTime.length - 2; i++) {
			unfamiliarWordsNum += AppPreference.getNewWordsFmDegree(this, i);
		}
		familiarWordsNum = AppPreference.getNewWordsFmDegree(this, WordFactory.wordReviewTime.length - 1);
		easyWordsNum = AppPreference.getNewWordsFmDegree(this, 6);

		startStudyButton = (Button) findViewById(R.id.start_study_button);
		startReviewButton = (Button) findViewById(R.id.start_review_button);
		consolidationButton = (Button) findViewById(R.id.consolidation_button);
		startHuanboButton = (LinearLayout) findViewById(R.id.start_huanbo_layout);
		difficultyWordsButton = (LinearLayout) findViewById(R.id.words_difficulty_layout);
		wordsFmDegreeButton = (LinearLayout) findViewById(R.id.words_book_degree_layout);

		roundProgress = (RoundProgress) findViewById(R.id.roundProgress);

	}

	public void initViews() {
		startStudyButton.setOnClickListener(clickListener);
		consolidationButton.setOnClickListener(clickListener);
		startReviewButton.setOnClickListener(clickListener);
		startHuanboButton.setOnClickListener(clickListener);
		difficultyWordsButton.setOnClickListener(clickListener);
		wordsFmDegreeButton.setOnClickListener(clickListener);
		roundProgress.setOnClickListener(clickListener);
		setMainDisplayData();
	}

	OnClickListener clickListener = new OnClickListener() {

		@Override
		public void onClick(View view) {
			if (view == startStudyButton) {
				ExamRunActivity.startActivity(mContext, OneWord.DEGREE_UNFAMILIAR, ExamRunActivity.STUDY_MODE);
				// finish();
			} else if (view == startReviewButton) {
				ReviewActivity.startActivity(mContext);
			} else if (view == consolidationButton) {
				if (wf.getNumberOfWordsForTestOfDegree(OneWord.DEGREE_UNFAMILIAR) > 0 && wf.getConsolidateWordsNum() > 0) {
					showConsolidateDialog();
				} else
					ExamConsolidateActivity.startActivity(mContext);
			} else if (view == startHuanboButton) {
				if (FileManager.hasNotDownloadedVoicePack(mContext, true))
					Toast.makeText(mContext, "有部分音频文件没有下载，可能会影响听音，建议去设置页面下载", Toast.LENGTH_LONG).show();
				else
					ExamHuanboActivity.startActivity(mContext);
			} else if (view == difficultyWordsButton) {
				WordsBookActivity.startActivityOnDifficultyWords(mContext);
			} else if (view == wordsFmDegreeButton) {
				WordsFmDegreeActivity.startActivity(mContext);
			} else if (view == roundProgress) {
				SettingPlanActivity.startActivity(mContext, StaticData.MODE_UPDATE);
			}
		}
	};

	private void showConsolidateDialog() {
		View view = LayoutInflater.from(this).inflate(R.layout.view_dialog_normal, null);
		TextView content = (TextView) view.findViewById(R.id.dialog_content);
		Button continueBtn = (Button) view.findViewById(R.id.dialog_btn_ok);
		Button cancel = (Button) view.findViewById(R.id.dialog_btn_cancel);
		content.setText("优先学习生词噢\n\n今天的生词学习任务还没有完成\n你确定要巩固熟词吗？");
		continueBtn.setText("继续");
		cancel.setText("取消");

		final MyDialog showConsolidateDialog = new MyDialog(this, view, R.style.mydialog, false);
		showConsolidateDialog.setCanceledOnTouchOutside(true);
		showConsolidateDialog.show();
		continueBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ExamConsolidateActivity.startActivity(mContext);
				showConsolidateDialog.dismiss();
			}
		});
		cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showConsolidateDialog.dismiss();
			}
		});
	}

	TextView nightmodeText;
	TextView nightmodeIcon;

	private boolean mIsQuiting;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 当列表为根节点时，确认是否退出
		boolean consumed = false;
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			consumed = true;
			if (isSlidingOpening()) {
				closeSlidingPane();
				mIsQuiting = false;
			} else if (mIsQuiting) {
				finish();
				System.out.println("软件被关闭了");
			} else {
				Toast.makeText(this, R.string.press_again_to_quit, Toast.LENGTH_SHORT).show();
				mIsQuiting = true;
				new Thread() {
					public void run() {
						try {
							sleep(3000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						mIsQuiting = false;
					};
				}.start();
			}
			break;
		}
		return consumed;
	}

	public static MainActivity getInstance() {
		return instance;
	}

	public static Context getContext() {
		return mContext;
	}

	private void studyMode() {
		startStudyButton.setVisibility(View.VISIBLE);
		startReviewButton.setVisibility(View.GONE);

		if (wf.getNumberOfWordsForTestOfDegree(OneWord.DEGREE_UNFAMILIAR) > 0) {
			startStudyButton.setVisibility(View.VISIBLE);
			startReviewButton.setVisibility(View.GONE);
		} else {
			startStudyButton.setVisibility(View.GONE);
			startReviewButton.setVisibility(View.VISIBLE);
		}
	}

	public void closeSlidingMenu() {
		mSlidingPaneLayout.closePane();
	}

	TextView newWordsTextView1, newWordsTextView2, newWordsTextView3;
	VariableTextView mVariableTextView;

	private void findViewsForNumDisplay() {
		newWordsTextView1 = (TextView) findViewById(R.id.new_words_textview1);
		newWordsTextView2 = (TextView) findViewById(R.id.new_words_textview2);
		newWordsTextView3 = (TextView) findViewById(R.id.new_words_textview3);
		mVariableTextView = (VariableTextView) findViewById(R.id.variableTextView);
	}

	private void initDisplays(boolean learningWords, boolean learningPhrase, int wordsDays, int phraseDays, int newWords, int familiarWords, int unLearnedWords) {
		mVariableTextView.setData(learningWords, learningPhrase, wordsDays, phraseDays);
		newWordsTextView1.setText("生词 " + newWords);
		newWordsTextView2.setText("熟词 " + familiarWords);
		newWordsTextView3.setText("未学 " + unLearnedWords);
	}

	boolean isLaunch = true;

	@SuppressLint("NewApi")
	private void roundProgressAnimation(int progress) {
		if (Utils.getCurrentVersion() < 11 || !isLaunch) {
			roundProgress.setProgress(progress);
			return;
		}
		isLaunch = false;
		final ValueAnimator mAnimator = ValueAnimator.ofInt(0, progress);
		mAnimator.addUpdateListener(new AnimatorUpdateListener() {
			@Override
			public void onAnimationUpdate(ValueAnimator animation) {
				int animatorValue = (Integer) animation.getAnimatedValue();
				if (animatorValue >= 0 && animatorValue <= roundProgress.getMax())
					roundProgress.setProgress(animatorValue);
			}
		});
		mAnimator.setDuration(2000);
		mAnimator.setInterpolator(new AnticipateOvershootInterpolator());
		mAnimator.setTarget(roundProgress);
		mAnimator.start();
	}
}
